package 设计模式.责任链模式;

/**
 * 责任链模式 示例
 * 模拟不同级别的日志输出
 */
public class Example_logger {
    public static void main(String[] args) {
        AbstractLogger debugLogger = new DebugLogger();
        AbstractLogger infoLogger = new InfoLogger();
        AbstractLogger errorLogger = new ErrorLogger();
        debugLogger.setNextLogger(infoLogger);
        infoLogger.setNextLogger(errorLogger);

        debugLogger.log(2,"哈哈哈");
    }
    static class DebugLogger extends AbstractLogger{
        public DebugLogger() { this.level = 1;}
        @Override
        public void write(String message) {
            System.out.println("DEBUG:"+message);
        }
    }
    static class InfoLogger extends AbstractLogger{
        public InfoLogger() { this.level = 2; }
        @Override
        public void write(String message) {
            System.out.println("INFO:"+message);
        }
    }
    static class ErrorLogger extends AbstractLogger{
        public ErrorLogger() { this.level = 3; }
        @Override
        public void write(String message) {
            System.out.println("ERROR:"+message);
        }
    }
    static abstract class AbstractLogger{
        protected int level;
        private AbstractLogger nextLogger;
        public abstract void write(String message);
        public void log(int level,String message){
            if(level <= this.level){
                write(message);
            }
            if(getNextLogger()!=null){
                getNextLogger().log(level,message);
            }
        }
        public AbstractLogger getNextLogger() {
            return nextLogger;
        }
        public void setNextLogger(AbstractLogger nextLogger) {
            this.nextLogger = nextLogger;
        }
    }

}
